package com.wmm.jhdriver;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.common.util.SPUtils;
import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import cz.msebera.android.httpclient.Header;

public class MainActivity extends AppCompatActivity {
    static final String TAG = "ScannerApiTest";
    @BindView(R.id.txt_number)
    TextView txtNumber;
    @BindView(R.id.btn_hc)
    Button btnHc;
    Intent intent ;
    Timer timer=null;
    private List<Bean> list=new ArrayList<>();
    private boolean cancle=true;
    TimerTask task;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what==1){
            }else{
                getLists();
            }
            super.handleMessage(msg);
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
//         程序打开的时候调用服务，只用调用一次即可，不需要在每个activity中都调用
//        intent = new Intent(this, ScannerService.class);
//        startService(intent);
        txtNumber.setText("当前工号: " + SPUtils.get(this, "UserName", "").toString());
        init();
        findViewById(R.id.exit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this,LoginActivity.class));
                finish();
            }
        });
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
           handler.sendEmptyMessage(0);
            }
        };
       timer.schedule(task,0,60000);
    }
    private void getLists(){
        Cursor cursor = MyApp.getInstance().query(SQLiteDbHelper.TABLE_STUDENT, null,
                "", null,
                null, null, null, null);

        // 不断移动光标获取值
        list.clear();
        while (cursor.moveToNext()) {
            // 直接通过索引获取字段值
            Bean bean=new Bean();
            bean.type=cursor.getString(0);
            bean.time=cursor.getString(2);
            bean.list=cursor.getString(1);
            bean.kehu=cursor.getString(4);
            bean.ydhao=cursor.getString(3);
            list.add(bean);
//            String stuName = cursor.getString(cursor.getColumnIndex("name"));
        }
        cursor.close();
        if(list.size()>0){
            //开始自动提交任务
            Bean bean=list.get(0);
            final List<GangPingBean> gangPingBeanList=new ArrayList<>();
            try {
                JSONArray jsonArray=new JSONArray(bean.list);
                if(jsonArray!=null){
                    for (int i=0;i<jsonArray.length();i++){
                        gangPingBeanList.add(new Gson().fromJson(jsonArray.getJSONObject(i).toString(),GangPingBean.class));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if(list.size()<0)
                return;
            submit(gangPingBeanList,bean.ydhao,bean.type,bean.time);
        }
    }
    private void submit(final List<GangPingBean> list, String ydhao, String type, final String time){
        JSONArray array=null;
        try {
            array=new JSONArray();
            JSONObject object;
            for(int i=0;i<list.size();i++){
                object=new JSONObject();
                object.put("gangpinghao",list.get(i).getGangPingHao());
                array.put(object);
            }
            object=new JSONObject();
            object.put("sFaYunDanHao",ydhao);
            object.put("sYu",SPUtils.get(this,"YuInfo","").toString());
            object.put("sYunshufangshi","1".equals(type)?"0":"1");
            object.put("GangPingHao",array.toString().replace("=",":"));
            RequestParams requestParams=new RequestParams();
            requestParams.put("sJson",object.toString().replace("=",":"));
            HttpUtils.post(Constant.DRIVER_LUODI_SUBMIT, requestParams, new TextHttpResponseHandler() {
                @Override
                public void onStart() {
                    super.onStart();
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                }
                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    try {
                        JSONObject object1=new JSONObject(responseString);
                        if(object1.getInt("success")==0){
                            MyApp.getInstance().delete(SQLiteDbHelper.TABLE_STUDENT,
                                    "time = ?", new String[]{time});
                        }else{
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    void init() {
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
//        stopService(intent);
        if(timer!=null&&cancle){
            timer.cancel();
            timer=null;
        }
    }

    @Override
    public void onBackPressed() {
        moveTaskToBack(false);
    }

    public void click(View view) {
        Intent intent = new Intent(this, CommonActivity.class);
        switch (view.getId()) {
            case R.id.btn_ld:
                intent.putExtra("type", "1");
                startActivity(intent);
                break;
            case R.id.btn_hc:
                intent.putExtra("type", "2");
                startActivity(intent);
                break;
            case R.id.btn_record:
                startActivity(new Intent(this, HistoryActivity.class));
        }
    }
}
